import { observable, action } from 'mobx';
import { message } from 'antd';
import { WeaForm, WeaTableNew } from 'comsMobx';
import { WeaLocaleProvider } from 'ecCom';
import * as Api from '../../apis/setting/mailTemplate';
import { ValidateForm } from './util';

const { TableStore } = WeaTableNew;
const getLabel = WeaLocaleProvider.getLabel;
const initalState = {
  previewVisible: false,
  previewFields: [],
  editTitle: '',
  editFields: [],
  editRichValue: '',
  editId: '',
  editType: '',
};
export default class TemplateStore {
  @observable templateTable = new TableStore();
  @observable previewForm = new WeaForm();
  @observable editForm = new WeaForm();
  @observable previewVisible = initalState.previewVisible;
  @observable previewFields = initalState.previewFields;
  @observable editTitle = initalState.editTitle; // 编辑--Dialog-Title
  @observable editRichValue = initalState.editRichValue; // 编辑--富文本值
  @observable editId = initalState.editId; // 打开编辑的id
  @observable editType = initalState.editType; // 编辑参数

  @action setStoreState = (params) => {
    Object.keys(params).forEach((key) => {
      this[key] = params[key];
    });
  }

  @action clear = () => this.setStoreState(initalState);

  @action getMailTemplate = (params, initPage = false) => {
    Api.getMailTemplate(params).then((res) => {
      initPage ? this.templateTable.getDatas(res.sessionkey) :
      this.templateTable.getDatas(res.sessionkey, 1);
    });
  }

  @action operateUserMailTemplate = (params) => {
    Api.operateUserMailTemplate(params).then((res) => {
      if (res.flag) this.getMailTemplate();
    });
  }

  @action getMailTemplateBean = async (params) => {
    let res = await Api.getMailTemplateBean(params);
    return res;
  }

  // 预览
  @action getEmailSysTemplateCondition = (params, callback) => {
    Api.getEmailSysTemplateCondition(params).then((res) => {
      this.previewForm.initFormFields(res.conditioninfo);
      this.previewFields = res.conditioninfo;
      if (callback) callback();
    });
  }

  // 编辑
  @action getEmailTemplateCondition = (params, callback) => {
    Api.getEmailTemplateCondition(params).then((res) => {
      this.editForm.initFormFields(res.conditioninfo);
      this.editFields = res.conditioninfo;
      if (callback) callback();
    });
  }

  @action onEditSubmit = (callback) => {
    ValidateForm(this.editForm, callback);
  }

  @action markUserMailTemplate = (params, callback) => {
    let formParams = this.editForm.getFormParams();
    params = { ...formParams, ...params };
    Api.markUserMailTemplate(params).then((res) => {
      if (res.flag) {
        message.success(getLabel(83551, '保存成功！'));
        if (callback) callback(res);
      } else {
        let errorMsg = res.message === 'repeat' ? getLabel('26603', '名称重复') : getLabel(21809, '保存失败，请重试！');
        message.error(errorMsg);
      }
    });
  }
}
